package com.tsingteng.cosfun.helper;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

import com.qiniu.pili.droid.shortvideo.PLMediaFile;
import com.qiniu.pili.droid.shortvideo.PLShortVideoComposer;
import com.qiniu.pili.droid.shortvideo.PLShortVideoRecorder;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTrimmer;
import com.qiniu.pili.droid.shortvideo.PLVideoFrame;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.bean.JoinCostarBean;
import com.tsingteng.cosfun.bean.OpusBean;
import com.tsingteng.cosfun.bean.VideoLocalBean;
import com.tsingteng.cosfun.bean.VideoSectionBean;
import com.tsingteng.cosfun.callback.OnCutVideoListener;
import com.tsingteng.cosfun.callback.OnInitGifListener;
import com.tsingteng.cosfun.ui.costar.CostarActivity;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.BitmapUtils;
import com.tsingteng.cosfun.utils.Command;
import com.tsingteng.cosfun.utils.CommandManager;
import com.tsingteng.cosfun.utils.DBUtils;
import com.tsingteng.cosfun.utils.FileDownUtils;
import com.tsingteng.cosfun.utils.FileUtil;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.TimeUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.utils.UIUtils;
import com.tsingteng.cosfun.utils.VideoAddCommand;
import com.tsingteng.cosfun.utils.VideoDeleteCommand;
import com.tsingteng.cosfun.utils.VideoOrderCommand;
import com.tsingteng.cosfun.utils.VideoSetCommand;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static android.media.ThumbnailUtils.OPTIONS_RECYCLE_INPUT;

/**
 * 描述 :拍摄工具类
 * 创建人: 肖利.
 * 时间:2018/9/18
 * qq(872179966)
 */

public class VideoHelper {

    public static final String TAG = "VideoHelper";
    public static final String VIDEO_STORAGE_DIR = FileUtil.getPath();//保存视屏的更目录//todo
    public static final String VIDEO_PATH = "videoPath";//c传视屏路径的标志
    public static final String VIDEO_TIME = "videoTime";
    public static final String VIDEO_ROTATE = "videoRotate";
    public static final String VIDEO_COMPOSED = VIDEO_STORAGE_DIR + "/composed_video/";//合成的视屏路径
    private static final String VIDEO_GIF_FILE_PATH = VIDEO_STORAGE_DIR + "/videoPic/" +System.currentTimeMillis()+LogonUtils.getProFildId()+ "composed.gif";//生成的gif
    public static final String VIDEO_LOCAL = "isCutVideo";
    public static final String EDITED_FILE_PATH = VIDEO_STORAGE_DIR + LogonUtils.getProFildId() + "edited.mp4";//编辑的视屏
    public static final String TRIM_FILE_PATH = VIDEO_STORAGE_DIR;
    private static final String VIDEO_DOWN_FILE = FileUtil.getPath()+"/down_video/";//合演下载视频的目录;
    public static final String VIDEO_CRASH_LOG = VIDEO_STORAGE_DIR;
    public static final int mEncodingBitrate = 2000*1024;//码率
    public static final String VIDEO_SHOOT = VIDEO_STORAGE_DIR+"/shootVideo/";//拍摄视屏的路径
    public static final String QINIU_HOST= "http";//七牛域名

    private JoinCostarBean joinCostarBean;
    private static VideoHelper INTENTCE = null;
    private ArrayList<String> videoPathList = new ArrayList<>();//视屏地址集合
    private ArrayList<Long> videoTimeList = new ArrayList<>();//视屏时间集合
    private int currentVideoPosition = -1;//当前点击的视屏索引(主要是翻拍的时候)
    private boolean isFanPai = false;//是否原生翻拍
    private String videoAudioPath;//音频地址
    private PLShortVideoRecorder mShortVideoRecorder;
    private CommandManager commendManger;//撤销栈
    private CommandManager commendFilterManger;//撤销栈
    private int playId = -1;
    private String videoType = "-1";
    private ArrayList<String> urlPath = new ArrayList<>();//原视频的地址
    private int viewPosition = -1;
    private boolean isDown = false;
    private long activityId = -1;
    private int readCount;
    private OpusBean mOpusBean;
    private JoinCostarBean mJoinCostarBean;
    private FragmentActivity fragment;
    private OnLocalVideoListener onLocalVideoListener;
    private Dialog loadingDialog;
    private String direct;
    private static long DURTION_TIME = 400;//剪辑的视频长度
    public static long MORE_DURTION_TIME = 500;//多拍的视频长度
    private int time = 0;




    private VideoHelper() {

    }


    public static VideoHelper getIntence() {
        if (INTENTCE == null) {
            synchronized (VideoHelper.class) {
                if (INTENTCE == null) {
                    INTENTCE = new VideoHelper();
                }
            }
        }
        return INTENTCE;
    }


    /**
     * 滤镜manger
     */
    public CommandManager getCommendFilterManger() {
        return commendFilterManger;
    }

    public void setCommendFilterManger(CommandManager commendFilterManger) {
        this.commendFilterManger = commendFilterManger;
    }



    /**
     * 活动id
     */
    public long getActivityId() {
        return activityId;
    }


    /**
     * 活动id
     */
    public void setActivityId(long activityId) {
        this.activityId = activityId;
    }

    /**
     * OpusBean
     */
    public OpusBean getmOpusBean() {
        return mOpusBean;
    }

    /**
     * OpusBean
     */
    public void setmOpusBean(OpusBean opusBean) {
        this.mOpusBean = opusBean;
    }
    /**
     * mJoinCostarBean
     */
    public JoinCostarBean getmJoinCostarBean() {
        return mJoinCostarBean;
    }
    /**
     * mJoinCostarBean
     */
    public void setmJoinCostarBean(JoinCostarBean costarBean){
        this.mJoinCostarBean = costarBean;
    }

    /**
     * 设置当前要显示的索引(拍摄页面使用)
     */
    public int getViewPosition() {
        return viewPosition;
    }


    /**
     * 设置当前要显示的索引(拍摄页面使用)
     */
    public void setViewPosition(int viewPosition) {
        this.viewPosition = viewPosition;
    }

    /**
     * 有的话传便当id
     */
    public int getPlayId() {
        return playId;
    }

    /**
     * 设置便当id
     */
    public void setPlayId(int playId) {
        this.playId = playId;
    }

    /**
     * 保存视屏的标志(存video使用)
     */
    public String getVideoType() {
        return videoType;
    }

    public void setVideoType(String videoType) {
        this.videoType = videoType;
    }

    /**
     * 设置一下撤销栈
     */
    public void setCommendManger(CommandManager commendManger) {
        this.commendManger = commendManger;
    }

    /**
     * 得到撤销栈
     */
    public CommandManager getCommendManger() {
        if (commendManger == null) {
            return new CommandManager();
        }
        return commendManger;
    }


    /**
     * 得到当前点击的索引
     */
    public int getCurrentVideoPosition() {
        return currentVideoPosition;
    }

    /**
     * 设置当前点击的索引(添加视频和删除视屏的时候讲索引设置为-1)
     */
    public void setCurrentVideoPosition(int currentVideoPosition) {
        LogUtils.e(TAG, "将当前的索引设置为" + currentVideoPosition);
        this.currentVideoPosition = currentVideoPosition;
    }

    /**
     * 当当前的索引不是-1的时候,判断是否是翻拍还是自由拍摄
     */
    public boolean isFanPai() {
        return isFanPai;
    }

    /**
     * 设置翻拍还是自由的拍摄
     */
    public void setFanPai(boolean fanPai) {
        LogUtils.e(TAG, "设置为翻拍");
        isFanPai = fanPai;
    }
    /**
     * 设置原生翻拍的音频
     */
    public void setVideoAudioPath(String audioPath) {
        this.videoAudioPath = audioPath;
    }

    /**
     * 得到原生翻拍的视屏
     */
    public String getVideoAudioPath() {
        return videoAudioPath;
    }


    /**
     * 添加一个视频片段
     */
    public boolean addVideoInfo(String videoPath, long videoTime) {
        return addVideoInfo(videoPath, videoTime, getVideoInfoSize());
    }

    /**
     * 添加一个视频片段
     */
    public boolean addVideoInfo(String videoPath, long videoTime, int index) {
        //如果为空的话直接创建一个新的bean类,并初始化信息
        if (joinCostarBean == null) {
            joinCostarBean = new JoinCostarBean();
            joinCostarBean.setOriginal(true);//是否是原创
            joinCostarBean.setModification(true);//视屏修改了
            joinCostarBean.setProfileId(LogonUtils.getProFildId());
            joinCostarBean.setCreateTime(TimeUtils.getCurTimeLong());
            LogUtils.e(TAG, "joinCostarBean为空,重新创建");
            //将数据保存到数据库中
          DBUtils.saveJoinCostarBean(videoType, joinCostarBean);
            LogUtils.e(TAG, "保存joinCostarBean到数据库"  + " videoType ==  " + videoPath);
        }

        //只有当真正添加了一条数据之后我们才认为视屏信息修改了
        if (!TextUtils.isEmpty(videoPath)) {
            joinCostarBean.setModification(true);//视屏修改了
        }
        if (isDown) {
            //将数据保存到数据库中,开始下载的视屏不保存在草稿中 ,只有将视屏信息真正更改了之后才将信息保存在草稿箱中
             DBUtils.saveJoinCostarBean(videoType, joinCostarBean);
            isDown = false;
            LogUtils.e(TAG, "保存joinCostarBean到数据库"  + " videoType ==  " + getVideoType());
        }
        List<VideoSectionBean> videoSectionBeanArrayList = joinCostarBean.getVideoSectionInfos();
        if (videoSectionBeanArrayList == null) videoSectionBeanArrayList = new ArrayList<>();
        VideoSectionBean videoSectionBean = new VideoSectionBean();
        videoSectionBean.setUrlCover(BitmapUtils.saveBitmap(getVideoThumbnail(videoPath)));
        videoSectionBean.setSectionVideoUrl(videoPath);
        videoSectionBean.setLocalUrl(videoPath);
        videoSectionBean.setModification(true);
        videoSectionBean.setOriginalProfileId(LogonUtils.getProFildId());
        videoSectionBean.setSectionVideoSpan((int) videoTime);
        videoSectionBean.setSectionIndex(index);
        videoSectionBean.setSectionStartPoint(getVideoTimeToIndex(index) == 0 ? 0 : getVideoTimeToIndex(index) + 1);
        videoSectionBean.setSectionEndPoint((int) (getVideoTimeToIndex(index) + videoTime));
        videoSectionBean.setCreateTime(TimeUtils.getCurTimeLong());
        try {
            videoSectionBeanArrayList.add(index, videoSectionBean);
        } catch (IndexOutOfBoundsException e) {
            LogUtils.e(TAG, e.getMessage());
        }
        joinCostarBean.setVideoSectionInfos(videoSectionBeanArrayList);
        //将当前的索引赋值为原始状态
        currentVideoPosition = -1;
        //重置翻拍的样式
        isFanPai = false;
        LogUtils.e(TAG, "添加了一个视频地址,索引为" + index);
        initVideoSelectBean();
        return true;
    }

    /**
     * 得到片段视屏的信息
     */
    public List<VideoSectionBean> getVideoSectionBeanList() {
        if (joinCostarBean == null) return new ArrayList<>();
        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        if (videoSectionInfos == null || videoSectionInfos.size() == 0) return new ArrayList<>();
        return videoSectionInfos;
    }

    /**
     * 更改视屏
     */
    public boolean setVideoInfo(String videoPath, long videoTime, int index) {
        if (joinCostarBean == null) return false;
        //只有当真正添加了一条数据之后我们才认为视屏信息修改了
        if (!TextUtils.isEmpty(videoPath)) {
            joinCostarBean.setModification(true);//视屏修改了
        }
        if (isDown) {
            //将数据保存到数据库中,开始下载的视屏不保存在草稿中 ,只有将视屏信息真正更改了之后才将信息保存在草稿箱中
             DBUtils.saveJoinCostarBean(videoType, joinCostarBean);
            isDown = false;
            LogUtils.e(TAG, "保存joinCostarBean到数据库"  + " videoType ==  " + getVideoType());
        }
        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        if (videoSectionInfos == null || videoSectionInfos.size() == 0 || index >= videoSectionInfos.size())
            return false;
        FileUtil.deleteFile(videoSectionInfos.get(index).getLocalUrl());//删除原来的视屏
        VideoSectionBean videoSectionBean = videoSectionInfos.get(index);
        videoSectionBean.setSectionVideoUrl(videoPath);
        videoSectionBean.setLocalUrl(videoPath);
        videoSectionBean.setUrlCover(BitmapUtils.saveBitmap(getVideoThumbnail(videoPath)));
        videoSectionBean.setOriginalProfileId(LogonUtils.getProFildId());
        videoSectionBean.setSectionVideoSpan((int) videoTime);
        videoSectionBean.setSectionIndex(index);
        videoSectionBean.setModification(true);
        videoSectionBean.setSectionStartPoint(getVideoTimeToIndex(index) == 0 ? 0 : getVideoTimeToIndex(index) + 1);
        videoSectionBean.setSectionEndPoint((int) (getVideoTimeToIndex(index) + videoTime));
        videoSectionBean.setCreateTime(TimeUtils.getCurTimeLong());
        try {
            videoSectionInfos.set(index, videoSectionBean);
        } catch (IndexOutOfBoundsException e) {
            LogUtils.e(TAG, videoSectionInfos.size() + "====setVideoInfo=====>" + index);
        }
        //将当前的索引赋值为原始状态
        currentVideoPosition = -1;
        //重置翻拍的样式
        isFanPai = false;
        LogUtils.e(TAG, "设置了一个视频地址,索引为" + index);
        initVideoSelectBean();
        return true;
    }


    /**
     * 根据index删除移除视屏
     */
    public boolean removeVideoInfo(int index) {
        if (joinCostarBean == null) return false;
        joinCostarBean.setModification(true);//视屏修改了
        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        if (videoSectionInfos == null || videoSectionInfos.size() == 0 || index >= videoSectionInfos.size())
            return false;

        try {
            videoSectionInfos.remove(index);
            videoPathList.remove(index);
            videoTimeList.remove(index);
        } catch (IndexOutOfBoundsException e) {
            LogUtils.e(TAG, videoSectionInfos.size() + "====removeVideoInfo=====>" + index);
        }
        LogUtils.e(TAG, "移除了一个视频地址,索引为" + index);
        initVideoSelectBean();
        return true;
    }

    /**
     * 得到视屏的地址集合
     */
    public ArrayList<String> getVideoPathList() {
        if (videoPathList == null) videoPathList = new ArrayList<>();
        videoPathList.clear();
        if (joinCostarBean == null) return videoPathList;
        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        if (videoSectionInfos == null || videoSectionInfos.size() == 0) return videoPathList;
        for (int i = 0; i < videoSectionInfos.size(); i++) {
            videoPathList.add(videoSectionInfos.get(i).getLocalUrl());
        }
        LogUtils.e(TAG, "得到视屏的地址集合大小" + videoPathList.size());
        return videoPathList;
    }


    /**
     * 得到视屏的时间集合
     */
    public ArrayList<Long> getVideoTimeList() {
        if (videoTimeList == null) videoTimeList = new ArrayList<>();
        videoTimeList.clear();
        if (joinCostarBean == null) return videoTimeList;
        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        if (videoSectionInfos == null || videoSectionInfos.size() == 0) return videoTimeList;
        for (int i = 0; i < videoSectionInfos.size(); i++) {
            videoTimeList.add(Long.valueOf(videoSectionInfos.get(i).getSectionVideoSpan()));
        }
        LogUtils.e(TAG, "得到视屏的时间集合大小" + videoTimeList.size());
        return videoTimeList;
    }

    /**
     * 得到视屏的时间byIndex
     */
    public long getVideoTimeByIndex(int index) {
        ArrayList<Long> videoTimeList = getVideoTimeList();
        if (videoTimeList == null || videoTimeList.size() == 0 || index >= videoTimeList.size())
            return 0L;
        Long videoTime = videoTimeList.get(index);
        LogUtils.e(TAG, "得到视屏的时间byIndex" + videoTime);
        return videoTime;
    }

    /**
     * 得到index之前的视屏的时间(设置开始时间和结束的时间)
     */
    public long getVideoTimeToIndex(int index) {
        long time = 0;
        ArrayList<Long> videoTimeList = getVideoTimeList();
        if (videoTimeList == null || videoTimeList.size() == 0) return 0L;
        for (int i = 0; i < index; i++) {
            time = time + videoTimeList.get(i);
        }
        LogUtils.e(TAG, "得到视屏的总时间" + time);
        return time;
    }

    /**
     * 得到视屏的地址byIndex
     */
    public String getVideoPathByIndex(int index) {
        ArrayList<String> videoPahtList = getVideoPathList();
        if (videoPahtList == null || videoPahtList.size() == 0 || index >= videoPahtList.size())
            return null;
        String videoPaht = videoPahtList.get(index);
        LogUtils.e(TAG, "得到视屏的地址byIndex" + videoPaht);
        return videoPaht;
    }

    /**
     * 得到视屏的总时间
     */
    public long getVideoListTime() {
        long time = 0;
        ArrayList<Long> videoTimeList = getVideoTimeList();
        if (videoTimeList == null || videoTimeList.size() == 0) return 0L;
        return getVideoTimeToIndex(videoTimeList.size());
//        return time;
    }

    /**
     * 得到视屏片段的总数
     */
    public int getVideoInfoSize() {
        if (joinCostarBean == null) return 0;
        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        if (videoSectionInfos == null || videoSectionInfos.size() == 0) return 0;
        int videoSize = videoSectionInfos.size();
        LogUtils.e(TAG, "得到视屏片段的总数" + videoSize);
        return videoSize;
    }

    /**
     * 是否已经保存了视屏
     */
    public boolean isSaveVideo(String videoPath) {
        ArrayList<String> videoPathList = getVideoPathList();
        if (videoPathList == null || videoPathList.size() == 0) return false;
        if (videoPathList.contains(videoPath)) {
            LogUtils.e(TAG, "已经保存了视屏");
            return true;

        } else {
            LogUtils.e(TAG, "没有保存视屏,去保存视屏,");
            return false;

        }
    }

    /**
     * 清除保存的空视频(一般合成的时候需要调用,要不然会报错)
     */
    public boolean clearEmptyVideoPath() {
        ArrayList<String> videoPathList = getVideoPathList();
        if (videoPathList == null || videoPathList.size() == 0) return false;
        for (int i = 0; i < videoPathList.size(); i++) {
            String videoPath = videoPathList.get(i);
            if (TextUtils.isEmpty(videoPath) || TextUtils.equals("", videoPath)) {
                //将保存的视屏移除
                removeVideoInfo(i);
                i--;
                LogUtils.e(TAG, "clearEmptyVideoPath===>" + i);
            }else {
                //判断视屏是否存在，除掉七牛的视屏
                File file = new File(videoPath);
                if (!videoPath.contains("http") && !file.exists()) {
                    //将保存的视屏移除
                    removeVideoInfo(i);
                    i--;
                    LogUtils.e(TAG, "clearErrorVideoPath===>" + i);
                }
            }

        }

        if (videoPathList.size() == 0) {
            LogUtils.e(TAG, "清除保存的空视频===>失败");
            return false;
        }

        //清空一下错误的视屏地址
        for (int i = 0; i < videoPathList.size(); i++) {
            if (!videoPathList.get(i).contains("mp4")) {
                removeVideoInfo(i);
                i--;
            }
            LogUtils.e(TAG, "清空一下错误的视屏地址===>" + i);
        }

        LogUtils.e(TAG, "清除保存的空视频===>成功");
        return true;
    }


    /**
     * 保存主视频
     */
    public boolean addMainVideoInfo(String videoPath) {
        if (joinCostarBean == null) {
            LogUtils.e(TAG, "保存主视频===>失败");
            return false;
        }
        joinCostarBean.setModification(true);
        joinCostarBean.setCreateTime(TimeUtils.getCurTimeLong());
        joinCostarBean.setVideoUrl(videoPath);
        joinCostarBean.setLocalUrl(videoPath);
        joinCostarBean.setVideoSectionCount(getVideoInfoSize());
        joinCostarBean.setVideoSpan((int) getVideoListTime());
        LogUtils.e(TAG, "保存主视频===>成功");
        initVideoSelectBean();
        return true;
    }


    /**
     * 整理一下视频片段信息
     */
    public void initVideoSelectBean() {
        if (joinCostarBean == null) return;
        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        for (int i = 0; i < videoSectionInfos.size(); i++) {
            VideoSectionBean videoSectionBean = videoSectionInfos.get(i);
            videoSectionBean.setSectionVideoSpan((int) VideoHelper.getIntence().getVideoTimeByIndex(i));
            if (i == 0) {
                videoSectionBean.setSectionStartPoint(0);
            } else {
                videoSectionBean.setSectionStartPoint(videoSectionInfos.get(i - 1).getSectionEndPoint() + 1);
            }
            videoSectionBean.setSectionEndPoint((int) videoSectionBean.getSectionStartPoint() + videoSectionBean.getSectionVideoSpan());
            videoSectionBean.setSectionVideoUrl(VideoHelper.getIntence().getVideoPathByIndex(i));
            videoSectionBean.setLocalUrl(VideoHelper.getIntence().getVideoPathByIndex(i));
            videoSectionBean.setSectionIndex(i + 1);
            if (videoSectionBean.getOriginalProfileId() == 0) {
                videoSectionBean.setOriginalProfileId(joinCostarBean.getProfileId());
            } else {
                videoSectionBean.setOriginalProfileId(videoSectionBean.getOriginalProfileId());
            }
        }
    }

    /**
     * 得到主视频

     */
    public JoinCostarBean getJoinCostarBean() {
        if (joinCostarBean == null) return null;
        return joinCostarBean;
    }


    /**
     * 根据地址得到视屏的图片

     */
    public Bitmap getVideoThumbnail(String videoPath) {

        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
        if (bitmap != null) {
            LogUtils.e(TAG, "getVideoThumbnail" + bitmap.getHeight());
            return ThumbnailUtils.extractThumbnail(bitmap, 300, 300, OPTIONS_RECYCLE_INPUT);
        }
        return null;
    }




    public void destroyVideoList() {
        if (videoPathList != null) {
            videoPathList.clear();
            videoPathList = null;
        }
        if (videoTimeList != null) {
            videoTimeList.clear();
            videoTimeList = null;
        }
        if (joinCostarBean != null) {
            joinCostarBean = null;
        }
        isFanPai = false;
        currentVideoPosition = -1;
        viewPosition = -1;
        LogUtils.e(TAG, "销毁视屏集合");
        commendManger = null;
    }

    /**
     * 正常拍摄进来
     */
    public void starVideoShoot(Activity activity) {
        destroyVideoList();
        playId = -1;
        setVideoType(String.valueOf(System.currentTimeMillis()));
        setCommendManger(new CommandManager());
        activity.startActivity(new Intent(activity, CostarActivity.class));
        activity.overridePendingTransition(R.anim.activity_up, R.anim.activity_down_alpha);

    }

    /**
     * 从段子翻拍进来
     */
    public void starVideoShootToPlay(Activity activity, int playId) {
        destroyVideoList();
        this.playId = playId;
        setVideoType(String.valueOf(System.currentTimeMillis()));
        setCommendManger(new CommandManager());
        activity.startActivity(new Intent(activity, CostarActivity.class));
        activity.overridePendingTransition(R.anim.activity_up, R.anim.activity_down_alpha);

    }


    /**
     * 从合拍进来
     */
    public void downVideo(Context context,String isActivity, JoinCostarBean oldJoinCostarBean, OnVideoHelperDowmVideoListener onVideoHelperDowmVideoListener) {
        destroyVideoList();
        isDown = true;
        this.joinCostarBean = oldJoinCostarBean;
        if (onVideoHelperDowmVideoListener != null) {
            onVideoHelperDowmVideoListener.onStartDown();
        }
        joinCostarBean.setIsActivity(isActivity);
        LogUtils.e(TAG, "开始下载:1");
        List<VideoSectionBean> videoSectionInfosSave;
        //初始化单例的videoHelper
        setVideoType(String.valueOf(System.currentTimeMillis()));
        setCommendManger(new CommandManager());
        urlPath = new ArrayList<>();//原始的视屏地址
        videoPathList = new ArrayList<>();//处理过的视屏地址
        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        for (int i = 0; i < videoSectionInfos.size(); i++) {
            String sectionVideoUrl = videoSectionInfos.get(i).getSectionVideoUrl();
            urlPath.add(sectionVideoUrl);
            videoPathList.add(VideoHelper.VIDEO_DOWN_FILE + splitVideoName(sectionVideoUrl));
            LogUtils.e(TAG, "处理好第" + i + "条视屏地址urlPath" + urlPath.size() + "videoPathList" + videoPathList.size());
        }
        videoSectionInfosSave = this.joinCostarBean.getVideoSectionInfos();
        if (videoSectionInfosSave != null && videoSectionInfosSave.size() > 0) {
            for (int i = 0; i < videoSectionInfosSave.size(); i++) {
                videoSectionInfosSave.get(i).setSectionVideoUrl(videoPathList.get(i));
                videoSectionInfosSave.get(i).setLocalUrl(videoPathList.get(i));
                LogUtils.e(TAG, "赋值好第" + i + "条视屏地址" + "videoPathList" + videoPathList.get(i));
            }
            LogUtils.e(TAG, "开始下载");
        }
        LogUtils.e(TAG, "开始下载:2");
        for (int i = 0; i < videoPathList.size(); i++) {
            File file = new File(videoPathList.get(i));
            if (file.exists()) {
                file.delete();
                LogUtils.e(TAG, "删除视屏url" + videoPathList.get(i));
            }
        }
        FileDownUtils.getIntance().startMoreDown(context, urlPath, videoPathList, new FileDownUtils.DownloadCallBack() {
            @Override
            public void onCompleted(String filename) {
                LogUtils.e(TAG, "开始下载onComplete");
                if (onVideoHelperDowmVideoListener != null) {
                    onVideoHelperDowmVideoListener.onComplete();
                    if (videoSectionInfosSave != null && videoSectionInfosSave.size() > 0) {
                        new Thread(() -> {
                            for (int i = 0; i < videoSectionInfosSave.size(); i++) {
                                videoSectionInfosSave.get(i).setUrlCover(BitmapUtils.saveBitmap(getVideoThumbnail(videoPathList.get(i))));
                                LogUtils.e(TAG, "赋值好第" + i + "条视屏地址" + "的bitMap" + videoPathList.get(i));
                            }
                        }).start();

                    }
                }
            }

            @Override
            public void onProgress(int progress, int speed) {

            }

            @Override
            public void onNumProgress(int progress, int downNum, int totalNum, int speed) {
                LogUtils.e(TAG, progress + "开始 下载progress");
                if (onVideoHelperDowmVideoListener != null) {
                    onVideoHelperDowmVideoListener.onPregress(progress);
                }
            }

            @Override
            public void onFail(String error) {
                if (onVideoHelperDowmVideoListener != null) {
                    onVideoHelperDowmVideoListener.onComplete();
                }
            }
        });


    }

    /**
     * 格式化视屏的地址
     */
    public String splitVideoName(String name) {
        String[] split = name.split("/");
        if (split.length == 0) return name;
        return split[split.length - 1];
    }

    public interface OnVideoHelperDowmVideoListener {
        void onStartDown();

        void onPregress(int pregress);

        void onComplete();
    }

    /**
     * 从草稿箱进图拍摄页面
     */
    public void startShootFormDraft(JoinCostarBean joinCostarBean) {
        destroyVideoList();
        this.joinCostarBean = joinCostarBean;
        setVideoType(joinCostarBean.getVideoType());
        VideoHelper.getIntence().setCommendManger(new CommandManager());
    }


    /**
     * 得到撤销具体的操作
     */
    public int getOperationPosition(int type, Activity context, Command command) {
        String operation = "";
        int position = 0;
        if (type == 1) {
            operation = "撤销";
        } else if (type == 2) {
            operation = "恢复";
        }
        String und0CommandName = command.getCommandName();
        if (TextUtils.equals(und0CommandName, "VideoAddCommand")) {
            AppUtils.showHintDialogToast(context, operation + "添加片段");
            position = ((VideoAddCommand) command).index;
        } else if (TextUtils.equals(und0CommandName, "VideoDeleteCommand")) {
            AppUtils.showHintDialogToast(context, operation + "删除片段");
            position = ((VideoDeleteCommand) command).index;
        } else if (TextUtils.equals(und0CommandName, operation + "更改片段")) {
            position = ((VideoSetCommand) command).index;
        } else if (TextUtils.equals(und0CommandName, operation + "排序片段")) {
            position = ((VideoOrderCommand) command).formIndex;
        }
        LogUtils.e(TAG, "command索引" + position);
        return position;
    }


    /**
     * 滤镜撤销工具video
     */
    public boolean getOperationFilter(int type, Activity context, Command command) {
        String operation = "";
        if (type == 1) {
            operation = "撤销";
        } else if (type == 2) {
            operation = "恢复";
        }
        String und0CommandName = command.getCommandName();
        if (TextUtils.equals(und0CommandName, "VideoFilterCommand")) {
            AppUtils.showHintDialogToast(context, operation + "滤镜");
            return true;
        } else {
            return false;
        }

    }

    public void setFragment(FragmentActivity fragment) {
        this.fragment = fragment;
    }

    public FragmentActivity getFragment() {
        return fragment;
    }

    public void setNotRead(int count) {
        this.readCount = count;
    }

    public int getNotRead() {
        return readCount;
    }

    public void setDirection(String direction) {
        this.direct = direction;
    }

    public String getDirect() {
        return direct;
    }

    /**
     * 得到本地的视屏
     */
    public void getLocalVideoList(Activity activity) {
        loadingDialog = DialogHelper.getLoadingDialog(activity);
        loadingDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (this != null) {
                    final boolean[] isAdd30 = {false};
                    final boolean[] isAdd60 = {false};
                    List<VideoLocalBean> list = null;
                    Cursor cursor = activity.getContentResolver().query(
                            MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null,
                            null, null);
                    if (cursor != null) {
                        list = new ArrayList<VideoLocalBean>();
                        while (cursor.moveToNext()) {
                            String title = cursor
                                    .getString(cursor
                                            .getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
                            String path = cursor
                                    .getString(cursor
                                            .getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                            long duration = cursor
                                    .getInt(cursor
                                            .getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
                            long size = cursor
                                    .getLong(cursor
                                            .getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
                            VideoLocalBean video = new VideoLocalBean();
                            video.setVideoCover(BitmapUtils.saveBitmap(getVideoThumbnail(path)));
                            video.setName(title);
                            video.setSize(size);
                            video.setUrl(path);
                            video.setDuration(duration);
                            list.add(video);
                            if (onLocalVideoListener != null) {
                                if (list.size() > 12 && !isAdd30[0]) {
                                    List<VideoLocalBean> finalList = list;
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            onLocalVideoListener.getVideoInfo30(finalList);
                                            loadingDialog.dismiss();
                                            isAdd30[0] = true;
                                        }
                                    });

                                }
                                if (list.size() > 50 && !isAdd60[0]) {
                                    List<VideoLocalBean> finalList = list;
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            onLocalVideoListener.getVideoInfo60(finalList);
                                            loadingDialog.dismiss();
                                            isAdd60[0] = true;
                                        }
                                    });

                                }
                            }
                        }
                        if (onLocalVideoListener != null) {
                            List<VideoLocalBean> finalList = list;
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!isAdd30[0]) {
                                        loadingDialog.dismiss();
                                        onLocalVideoListener.getVideoInfo30(finalList);
                                    }
                                    if (!isAdd60[0]) {
                                        onLocalVideoListener.getVideoInfo30(finalList);
                                    }
                                    onLocalVideoListener.getVideoInfoAll(finalList);
                                }
                            });
                        }
                        cursor.close();
                    }
                }
            }
        }).start();
    }

    public void setOnLocalVideoListener(OnLocalVideoListener onLocalVideoListener) {
        this.onLocalVideoListener = onLocalVideoListener;
    }

    public interface OnLocalVideoListener {

        void getVideoInfo30(List<VideoLocalBean> list);

        void getVideoInfo60(List<VideoLocalBean> list);

        void getVideoInfoAll(List<VideoLocalBean> list);
    }

    public List<VideoLocalBean> getList(Context context) {
        List<VideoLocalBean> sysVideoList = new ArrayList<>();
        // MediaStore.Video.Thumbnails.DATA:视频缩略图的文件路径
        String[] thumbColumns = {MediaStore.Video.Thumbnails.DATA,
                MediaStore.Video.Thumbnails.VIDEO_ID};
        // 视频其他信息的查询条件
        String[] mediaColumns = {MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DATA, MediaStore.Video.Media.DURATION};

        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media
                        .EXTERNAL_CONTENT_URI,
                mediaColumns, null, null, null);

        if (cursor == null) {
            return sysVideoList;
        }
        if (cursor.moveToFirst()) {
            do {
                VideoLocalBean info = new VideoLocalBean();
                int id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Video.Media._ID));
                Cursor thumbCursor = context.getContentResolver().query(
                        MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
                        thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID
                                + "=" + id, null, null);
                if (thumbCursor.moveToFirst()) {
                    info.setVideoCover(thumbCursor.getString(thumbCursor
                            .getColumnIndex(MediaStore.Video.Thumbnails.DATA)));
                }
                info.setUrl(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media
                        .DATA)));
                info.setDuration(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video
                        .Media.DURATION)));
                sysVideoList.add(info);
            } while (cursor.moveToNext());
        }
        return sysVideoList;
    }


    /**
     * 生成gif
     *
     * @param mShortVideoComposer
     * @param onInitGifListener
     */
    public void initGif(Activity activity, PLShortVideoComposer mShortVideoComposer, OnInitGifListener onInitGifListener) {
        UIUtils.runOnUIThread(() -> {
            time = 0;
            ToastUtils.showToast("根据机型不同,请耐心等候!");
            onInitGifListener.onStartGif();
        });

        final boolean[] isSuccess = {false};
        LogUtils.e(TAG, "开始生成gif图");
        new Thread(() -> {
            List<VideoSectionBean> videoSectionBeanList = getVideoSectionBeanList();
            String videoPath = null;
            if (TextUtils.equals(getJoinCostarBean().getIsActivity(),"1")) {
                for (int i = 0; i < videoSectionBeanList.size(); i++) {
                    if (videoSectionBeanList.get(i).isModification()) {
                        videoPath = videoSectionBeanList.get(i).getLocalUrl();
                        break;
                    }
                }
            } else {
                videoPath = videoSectionBeanList.get(0).getLocalUrl();
            }
            if (TextUtils.isEmpty(videoPath)) {
                UIUtils.runOnUIThread(() -> {
                    onInitGifListener.onFailGif();
                    return;
                });
            }
            LogUtils.e(TAG, "开始生成gif初始化成功");
            PLMediaFile mMediaFile = new PLMediaFile(videoPath);
            int videoFrameCount = mMediaFile.getVideoFrameCount(false);
            if (videoFrameCount > 5) {
                PLVideoFrame videoFrameByIndex0 = mMediaFile.getVideoFrameByIndex(0, false);
                PLVideoFrame videoFrameByIndex2 = mMediaFile.getVideoFrameByIndex(2, false);
                PLVideoFrame videoFrameByIndex4 = mMediaFile.getVideoFrameByIndex(4, false);
                if (videoFrameByIndex2 != null && videoFrameByIndex0 != null && videoFrameByIndex4 != null) {
                    Bitmap bitmap0 = videoFrameByIndex0.toBitmap();
                    Bitmap bitmap2 = videoFrameByIndex2.toBitmap();
                    Bitmap bitmap4 = videoFrameByIndex4.toBitmap();
                    List<Bitmap> bitmaps = new ArrayList<>();
                    bitmaps.add(bitmap0);
                    bitmaps.add(bitmap2);
                    bitmaps.add(bitmap4);
                    joinCostarBean.setWidth(bitmap0.getWidth());
                    joinCostarBean.setHeight(bitmap0.getHeight());
                    LogUtils.e(TAG, "开始生成gif图片生成成功,开始合成图片");
                       final Timer[] timer = {new Timer()};
                       final TimerTask[] task = {new TimerTask() {
                           @Override
                           public void run() {
                               LogUtils.e(TAG, "time" + time);
                               if (time > 5) {
                                   activity.runOnUiThread(() -> {
                                       if (isSuccess[0]) return;
                                       isSuccess[0] = true;
                                       timer[0].cancel();
                                       timer[0] = null;
                                       mShortVideoComposer.cancelComposeToGIF();
                                       onInitGifListener.onSuccessGif();
                                   });
                                   return;
                               }
                               if (time<5) {
                                   UIUtils.runOnUIThread(() -> onInitGifListener.onProgress(time*20));
                               }
                               time++;
                           }
                       }};
                       timer[0].schedule(task[0],100,1000);
                    mShortVideoComposer.composeToGIF(bitmaps, 500, true, VideoHelper.VIDEO_GIF_FILE_PATH, new PLVideoSaveListener() {
                        @Override
                        public void onSaveVideoSuccess(String s) {
                            UIUtils.runOnUIThread(() -> {
                                if (isSuccess[0])return;
                                isSuccess[0] = true;
                                LogUtils.e(TAG, "成功!" + s);
                                onInitGifListener.onSuccessGif();
                                joinCostarBean.setVideoGifUrl(s);
                            });
                        }

                        @Override
                        public void onSaveVideoFailed(int i) {
                            UIUtils.runOnUIThread(() -> {
                                if (    isSuccess[0])return;
                            isSuccess[0] = true;
                                LogUtils.e(TAG, "失败!" + i);
                                onInitGifListener.onFailGif();
                            });
//
                        }

                        @Override
                        public void onSaveVideoCanceled() {
                            UIUtils.runOnUIThread(() -> {
                                if (    isSuccess[0])return;
                                isSuccess[0] = true;
                                LogUtils.e(TAG, "取消!");
                                onInitGifListener.onFailGif();
                            });

                        }

                        @Override
                        public void onProgressUpdate(float v) {
                            UIUtils.runOnUIThread(() -> {
                                LogUtils.e(TAG, "进度!" + v);
                                onInitGifListener.onProgress((int) (v * 100));
                            });
                        }
                    });


                } else {
                    UIUtils.runOnUIThread(() -> onInitGifListener.onFailGif());

                }

            } else {

                UIUtils.runOnUIThread(() -> onInitGifListener.onFailGif());

            }
        }).start();
    }


    /**
     * 剪辑视屏
     */
    public void cutPreVideo(Activity activity, String mMp4path, OnCutVideoListener onCutVideoListener) {
        if (onCutVideoListener == null) return;
        onCutVideoListener.cutVideoStart();
        PLMediaFile mMediaFileOrgnal = new PLMediaFile(VideoHelper.getIntence().getVideoAudioPath());

        long orgnalVideo = mMediaFileOrgnal.getDurationMs();
        PLMediaFile mMediaFileFanPai = new PLMediaFile(mMp4path);
        long fanpaiVideo = mMediaFileFanPai.getDurationMs();
        PLShortVideoTrimmer mShortVideoTrimmer = new PLShortVideoTrimmer(activity, mMp4path, VideoHelper.VIDEO_SHOOT + System.currentTimeMillis() + "trimmed.mp4");
        mShortVideoTrimmer.trim(DURTION_TIME, orgnalVideo + DURTION_TIME + 80, PLShortVideoTrimmer.TRIM_MODE.ACCURATE, new PLVideoSaveListener() {

            @Override
            public void onSaveVideoSuccess(String s) {
                UIUtils.runOnUIThread(() -> {
                    FileUtil.deleteFile(mMp4path);//删除原先的视屏
                    onCutVideoListener.cutVideoSuccess(s);
                });

            }

            @Override
            public void onSaveVideoFailed(int i) {
                UIUtils.runOnUIThread(() -> onCutVideoListener.cutVideoFail(i));

            }

            @Override
            public void onSaveVideoCanceled() {
                UIUtils.runOnUIThread(onCutVideoListener::cutVideoCancel);

            }

            @Override
            public void onProgressUpdate(float v) {
                UIUtils.runOnUIThread(() -> onCutVideoListener.cutVideoProgress((int) (v * 100)));

            }
        });
    }


}
